import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<User | null>(null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)

  // 保存认证信息到本地存储
  const saveAuthToStorage = (authToken: string, user: User) => {
    localStorage.setItem('user_token', authToken)
    localStorage.setItem('user_info', JSON.stringify(user))
  }

  // 清除本地存储的认证信息
  const clearAuthFromStorage = () => {
    localStorage.removeItem('user_token')
    localStorage.removeItem('user_info')
  }

  // 初始化（从本地存储恢复状态）
  const initializeAuth = () => {
    const savedToken = localStorage.getItem('user_token')
    const savedUserInfo = localStorage.getItem('user_info')
    
    if (savedToken) {
      token.value = savedToken
    }
    
    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        localStorage.removeItem('user_info')
      }
    }
  }

  // 登录
  const login = (authToken: string, user: User): void => {
    token.value = authToken
    userInfo.value = user
    saveAuthToStorage(authToken, user)
  }

  // 注册
  const register = (authToken: string, user: User): void => {
    token.value = authToken
    userInfo.value = user
    saveAuthToStorage(authToken, user)
  }

  // 退出登录
  const logout = (): void => {
    token.value = ''
    userInfo.value = null
    clearAuthFromStorage()
  }

  // 设置用户信息
  const setUserInfo = (user: User): void => {
    userInfo.value = user
    if (token.value) {
      localStorage.setItem('user_info', JSON.stringify(user))
    }
  }

  // 设置token
  const setToken = (authToken: string): void => {
    token.value = authToken
    localStorage.setItem('user_token', authToken)
  }

  // 初始化
  initializeAuth()

  return {
    // 状态
    token,
    userInfo,
    
    // 计算属性
    isLoggedIn,
    
    // 方法
    login,
    register,
    logout,
    setUserInfo,
    setToken,
    initializeAuth
  }
})